import File from './File';
import Context from '../Context';
import fs = require('fs');
import BaseSourceFile from './BaseSourceFile';
import TemplateFile from './TemplateFile';


export default class SourceFile extends BaseSourceFile {
    public readonly type = FileType.source;

    constructor(cx: Context, op: CreateFileOptions) {
        super(cx, op);
    }

    async doLoad() {
        await super.doLoad();
        for (let h of this.cx.pageTemplate) {
            if (this.id.match(h.match)) {
                let dest = this.id;
                if (h.path) {
                    dest = this.id.replace(h.match, h.path);
                } else {
                    dest += '.html';
                }
                let opt = {
                    entry: this.id,
                    external: this.cx.options.external,
                    preload: this.cx.options.preload
                };
                let f = new TemplateFile(this.cx, {
                    src: h.template,
                    id: dest
                }, async (s, d) => s.replace(
                    'ZPackConfigPlaceHolder',
                    JSON.stringify(opt).replace(/"/g, '&quot;').replace(/'/g, '&apos;')
                ));
                this.extraFiles.push(f);
            }
        }
    }
}
